package leetcode;

public class NumberofIslands {
	public void connect(char[][] grid, int x,int y){
		if(x>=0 && x<grid.length && y>=0 && y<grid[0].length && grid[x][y]=='1'){
			grid[x][y] = '0';
			connect(grid, x-1, y);
			connect(grid, x+1, y);
			connect(grid, x, y-1);
			connect(grid, x, y+1);
		}
	}
	public int numIslands(char[][] grid) {
		if(grid==null || grid.length==0 || grid[0].length==0)
			return 0;
		int count = 0;
		for(int i=0;i<grid.length;i++){
			for(int j=0;j<grid[0].length;j++){
				if(grid[i][j]=='1'){
					connect(grid, i, j);
					count++;
				}
			}
		}
		
		
		return count;
	}
	public static void main(String[] argsStrings){
		NumberofIslands numberofIslands = new NumberofIslands();
		char[][] grid = {
				{'1','0','0','0','0'},
				{'0','1','0','1','0'},
				{'0','0','1','1','0'},
				{'0','0','0','0','1'}
		};
		System.out.println(numberofIslands.numIslands(grid));
		
	}
}
